use std::env;

use common::{agent, compose::make_empty_ctx};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum TransError {
    #[error("Deepseek API key not found")]
    ApiKeyNotFound,
    #[error("Deepseek API error: {0}")]
    ApiError(String),
}

pub enum TransLang {
    En,
    Zh,
}

pub async fn trans(input: &str, target: TransLang) -> Result<String, TransError> {
    // 从环境变量获取API密钥，如果没有设置则跳过测试
    let api_key = env::var("DEEPSEEK_API_KEY").map_err(|_| TransError::ApiKeyNotFound)?;

    let system = match target {
        TransLang::En => "You are a English translator, I want you to act as a English translator, translate the following text to English: \n\n",
        TransLang::Zh => "You are a Chinese translator, I want you to act as a Chinese translator, translate the following text to Chinese: \n\n",
    };
    let ai_agent = agent::init_agent(system, &api_key);

    let response = ai_agent.run(input.to_string(), make_empty_ctx()).await.map_err(|e| TransError::ApiError(e.to_string()))?;
    Ok(response)
}


#[cfg(test)]
mod tests {
    use super::*;
    use dotenvy::dotenv;

    #[tokio::test]
    async fn test_trans() {
        dotenv().ok();
        let input = "你好";
        let target = TransLang::En;
        let output = trans(input, target).await.unwrap();
        println!("{}", output);
    }

    #[tokio::test]
    async fn test_trans_file() {
        dotenv().ok();
        // 读取文件
        let input_file_name = "D:/rust-doc/inline-assembly.md";
        let output_file_name = "D:/rust-doc/inline-assembly-zh.md";
        let file = std::fs::read_to_string(input_file_name).unwrap();

        
        // 翻译
        let target = TransLang::Zh;
        let output = trans(&file, target).await.unwrap();
        
        
        // 将结果追加到文件中
        use std::fs::OpenOptions;
        use std::io::Write;
        
        let mut file = OpenOptions::new()
            .write(true)
            .append(true)
            .create(true)
            .open(output_file_name)
            .unwrap();
            
        writeln!(file, "{}", output).unwrap();
        println!("翻译结果已追加到文件: {}", output_file_name);
    }
}